<template>
  <div class="supplier-product-type">
    <h1>产品类型列表页面</h1>
    <div class="table-container">
      <el-table :data="productTypeList" style="width: 100%" border>
        <el-table-column prop="id" label="类型ID" width="150" />
        <el-table-column prop="categoryName" label="类型名称" width="150" />
        <el-table-column prop="status" label="状态" width="150">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="230">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="230">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteProductType(scope.row)"
              :disabled="scope.row.status === 2">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container" style="margin-top: 10px; text-align: right;">
        <el-pagination
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
          :current-page="pagination.pageNo"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getProductCategoryListAPI, updateProductCategoryStatusAPI, deleteProductCategoryAPI } from '@/apis/supplier'

export default {
  name: 'SupplierProductType',
  data() {
    return {
      productTypeList: [],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  created() {
    this.fetchProductTypeList()
  },
  methods: {
    async fetchProductTypeList() {
      try {
        const res = await getProductCategoryListAPI({
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize
        })
        
        this.productTypeList = res.data?.records || []
        this.pagination.total = res.data?.total || 0
      } catch (error) {
        console.error('获取产品类型列表失败:', error)
        this.$message.error(error.data?.msg || '获取产品类型列表失败')
        this.productTypeList = []
      }
    },
    
    handlePageChange(pageNo) {
      this.pagination.pageNo = pageNo
      this.fetchProductTypeList()
    },
    
    handlePageSizeChange(pageSize) {
      this.pagination.pageSize = pageSize
      this.pagination.pageNo = 1
      this.fetchProductTypeList()
    },
    
    getStatusType(status) {
      switch (status) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        case 2:
          return 'info'
        default:
          return 'info'
      }
    },
    
    getStatusText(status) {
      switch (status) {
        case 0:
          return '禁用'
        case 1:
          return '启用'
        case 2:
          return '已删除'
        default:
          return '未知'
      }
    },
    
    // 新增：时间格式化方法
    formatDateTime(isoString) {
      if (!isoString) return '';
      
      const date = new Date(isoString);
      
      // 补零函数
      const padZero = (num) => num.toString().padStart(2, '0');
      
      const year = date.getFullYear();
      const month = padZero(date.getMonth() + 1); // 月份从0开始
      const day = padZero(date.getDate());
      const hours = padZero(date.getHours());
      const minutes = padZero(date.getMinutes());
      const seconds = padZero(date.getSeconds());
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    async toggleStatus(row) {
      if (row.status === 2) {
        this.$message.warning('已删除的产品类型不能切换状态')
        return
      }
      
      try {
        const newStatus = row.status === 1 ? 0 : 1
        await updateProductCategoryStatusAPI({
          id: row.id,
          status: newStatus
        })
        
        row.status = newStatus
        // 更新时间格式
        row.updateTime = new Date().toISOString()
        
        this.$message.success(`${newStatus === 1 ? '启用' : '禁用'}成功`)
      } catch (error) {
        console.error('更新状态失败:', error)
        this.$message.error(error.data?.msg || '更新状态失败')
      }
    },
    
    async deleteProductType(row) {
      if (row.status === 2) {
        this.$message.warning('该产品类型已删除')
        return
      }
      
      this.$confirm('此操作将删除该产品类型, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteProductCategoryAPI(row.id)
          row.status = 2
          // 更新时间格式
          row.updateTime = new Date().toISOString()
          this.$message.success('删除成功!')
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error(error.data?.msg || '删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>


<style scoped>
.supplier-product-type {
  padding: 20px;
  background-color: #f5f5f5;
}

.supplier-product-type h1 {
  margin-top: 0;
  color: #2c3e50;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
}
</style>